<template>
  <div class="address-list">
    <header class="page-header">
      <span class="back" @click="goBack">＜</span>
      <h1 class="title">地址管理</h1>
    </header>
    <div 
      v-for="(item, index) in addressList" 
      :key="item.id || index" 
      class="address-item"
    >
      <div class="address-info">
        <p class="address-detail">
          {{ item.name }} {{ item.phone }}
        </p>
        <p class="address-detail">
          {{ item.address }}
        </p>
      </div>
      <div class="operation">
        <span 
          v-if="!item.is_default" 
          class="set-default" 
          @click="setDefault(index)"
        >
          设置默认
        </span>
        <span class="edit" @click="edit(item.id)">编辑</span>
      </div>
    </div>
    <button class="add-address" @click="addAddress">新增地址</button>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/history'

const router = useRouter()
const addressList = ref([])

// 获取地址列表
onMounted(async () => {
  try {
    const response = await api.get('/getaddress')
    console.log('地址数据:', response)
    if (response.status === 200) {
      addressList.value = response.data || []
    }
  } catch (error) {
    console.error('获取地址数据失败:', error)
  }
})

// 设置默认地址
const setDefault = async (index) => {
  try {
    const selectedAddress = addressList.value[index]
    const response = await api.post('/setDefaultAddress', {
      id: selectedAddress.id
    })
    
    if (response.status === 200) {
      // 更新本地数据
      addressList.value.forEach((item, i) => {
        item.is_default = i === index
      })
    } else {
      console.error('设置默认地址失败:', response.message)
    }
  } catch (error) {
    console.error('设置默认地址请求失败:', error)
  }
}

// 编辑地址
const edit = (addressId) => {
  router.push({
    name: 'edit',
    params: { addressId } // 传递地址 ID
  })
}
const goBack = () => {
  router.go(-1)
}

// 添加地址
const addAddress = () => {
  router.push('/address')
}
</script>

<style scoped>
.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.back {
  font-size: 24px;
  cursor: pointer;
  margin-right: 10px;
  color: #333;
}
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
/* 保持原样式不变 */
.address-list {
  width: 100%;
}
.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.address-info {
  flex: 1;
}
.address-detail {
  margin: 0;
  font-size: 14px;
  color: #333;
}
.contact-info {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #666;
}
.operation {
  display: flex;
  gap: 10px;
}
.set-default,
.edit {
  cursor: pointer;
  color: #007bff;
  font-size: 12px;
}
.add-address {
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #f40;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
    